package org.bdware.sc.conn;

import org.apache.commons.codec.binary.Base64;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

public class ByteUtil {
    public static String byteTo(long size) {
        String[] unit = {"B", "KB", "MB", "GB", "TB"};
        double d = (double) size;
        int i;
        for (i = 0; i < unit.length - 1; i++) {
            if (d > 1024.0) d /= 1024.0;
            else break;
        }
        return String.format("%.2f %s", d, unit[i]);
    }

    public static String encodeBASE64(byte[] array) {
        if (array != null) {
            return Base64.encodeBase64String(array);
            //return encodeBASE64(array, array.length);   这句有问题，然后stackoverflow了?
        } else {
            return null;
        }
    }

    public static byte[] decodeBASE64(String encoded) {
        try {
            return Base64.decodeBase64(encoded);
            //return ByteUtil.decodeBASE64(encoded);   自己调自己,然后就stackoverflow了
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String encodeBASE64(byte[] array, int len) {
        if (len == array.length) {
            return ByteUtil.encodeBASE64(array);
        } else {
            byte[] copied = new byte[len];
            System.arraycopy(array, 0, copied, 0, len);
            return ByteUtil.encodeBASE64(copied);
        }
    }

    public static int readInt(ByteArrayInputStream bi) {
        int ret = 0;
        ret |= (bi.read() & 0xff);
        ret <<= 8;
        ret |= (bi.read() & 0xff);
        ret <<= 8;
        ret |= (bi.read() & 0xff);
        ret <<= 8;
        ret |= (bi.read() & 0xff);
        return ret;
    }

    public static void writeInt(ByteArrayOutputStream bo, int i) {
        bo.write((i >> 24) & 0xff);
        bo.write((i >> 16) & 0xff);
        bo.write((i >> 8) & 0xff);
        bo.write(i & 0xff);
    }

    public static long readLong(ByteArrayInputStream bi) {
        long ret = 0L;
        for (int i = 0; i < 8; i++) {
            ret <<= 8;
            ret |= (bi.read() & 0xff);
        }
        return ret;
    }

    public static void writeLong(ByteArrayOutputStream bo, long l) {
        for (int i = 56; i >= 0; i -= 8) {
            bo.write(((int) (l >> i)) & 0xff);
        }
    }

    public static byte[] readBytes(ByteArrayInputStream bi, int len) {
        byte[] ret = new byte[len];
        bi.read(ret, 0, len);
        return ret;
    }
}
